package com.boot.service.impl;

import com.boot.mapper.CityMapper;
import com.boot.po.CityPo;
import com.boot.service.CityService;
import com.mysql.jdbc.TimeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>@description:</p>
 *
 * @projectName: spring-boot-redis
 * @packageName: com.boot.service.impl
 * @className:
 * @author: shuangyang
 * @date: 17-7-9 下午9:22
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CityServiceImpl implements CityService {

    private final CityMapper cityMapper;

    private final RedisTemplate redisTemplate;

    @Override
    public CityPo getTest(int id) {
        try {
            String key="city_own"+id;
            ValueOperations<String, CityPo> operations = redisTemplate.opsForValue();
            // 缓存存在
            boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey) {
                CityPo cityPo = operations.get(key);
                return cityPo;
            }
            CityPo cityPo = cityMapper.selectByPrimaryKey(id);
            //插入缓存
            operations.set(key, cityPo,100, TimeUnit.SECONDS);

            return cityPo;
        }catch (Exception e){
            e.fillInStackTrace();
        }
      return null;
    }

}
